package com.jtlrm.ckd.mvp.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.sdk.base.net.CommonObserver;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chatuidemo.db.NewUserDao;
import com.hyphenate.chatuidemo.domain.NewUserEntity;
import com.hyphenate.chatuidemo.ui.ChatActivity;
import com.hyphenate.easeui.model.EasePreferenceManager;
import com.hyphenate.easeui.widget.EaseExpandGridView;
import com.hyphenate.easeui.widget.EaseSwitchButton;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.GroupDetailEntity;
import com.jtlrm.ckd.entity.GroupMemberEntity;
import com.jtlrm.ckd.entity.event.DeleteGroupMessage;
import com.jtlrm.ckd.entity.event.UpdateGroupMessage;
import com.jtlrm.ckd.mvp.model.SuiFangModel;
import com.jtlrm.ckd.mvp.model.dao.UserHelper;
import com.jtlrm.ckd.mvp.view.adapter.GroupDetailAdapter;
import com.jtlrm.ckd.util.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@Route(path = "/person/info/group/detail")
public class MyGroupDetailActivity extends TitleBarActivity implements View.OnClickListener {

    @BindView(R.id.gridview)
    EaseExpandGridView gridView;
    GroupDetailAdapter adapter;
    ArrayList<GroupMemberEntity> memberEntities = new ArrayList<>();
    @BindView(R.id.rl_switch_block_offline_message)
    RelativeLayout blockOfflineLayout;
    @BindView(R.id.switch_block_offline_message)
    EaseSwitchButton offlinePushSwitch;
    String imGroupId;
    String groupId;
    @BindView(R.id.add_member)
    ImageView addMemberI;
    private EMGroup group;
    SuiFangModel suiFangModel;
    @BindView(R.id.group_name_label)
    TextView groupNameLabelT;
    @BindView(R.id.group_name_content)
    TextView groupNameContentT;
    @BindView(R.id.btn_exit_grp)
    Button exitGroupB;
    boolean isOwner = false;// 是否是群组
    GroupDetailEntity groupDetailEntity;
    NewUserDao userDao;
    @BindView(R.id.rl_change_group_name)
    RelativeLayout groupNameR;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        imGroupId = getIntent().getStringExtra("groupId");
        group = EMClient.getInstance().groupManager().getGroup(imGroupId);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTitleText() {
        return "群成员";
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_my_group_detail);
        ARouter.getInstance().inject(this);
    }

    @Override
    protected void initView() {
        if (group == null) {
            return;
        }
        if (group.getOwner().equals(UserHelper.getInstance(context).getUserInfo().getEasemobId() + "")) {
            isOwner = true;
            addMemberI.setVisibility(View.VISIBLE);
            groupNameLabelT.setText("修改群名称");
            groupNameR.setEnabled(true);
        } else {
            groupNameR.setEnabled(false);
            groupNameLabelT.setText("群名称");
            addMemberI.setVisibility(View.GONE);
        }
        suiFangModel = new SuiFangModel();
        adapter = new GroupDetailAdapter(context, R.layout.group_detail_item, memberEntities, group);
        gridView.setAdapter(adapter);
        if (EasePreferenceManager.getInstance().groupIsClose(imGroupId)) {
            offlinePushSwitch.closeSwitch();
        } else {
            offlinePushSwitch.openSwitch();
        }
        EventBusUtil.register(this);
        userDao = new NewUserDao();
    }

    @Override
    protected void obtainData() {
        showLoadingDialog("加载中");
        queryGroupDetail();
    }

    private void queryGroupDetail() {
        suiFangModel.queryGroupDetail(imGroupId, UserHelper.getInstance(context).getUserId(), new CommonObserver<GroupDetailEntity>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(GroupDetailEntity data) {
                groupDetailEntity = data;
                groupId = data.getId();
                if (data.getGroupType() == 1) {
                    // 等于默认群
                    exitGroupB.setVisibility(View.GONE);
                } else {
                    exitGroupB.setVisibility(View.VISIBLE);
                }
                if (groupDetailEntity == null) {
                    return;
                }
                setText(groupNameContentT, data.getName());
                queryMemeber();
            }
        }, lifecycleSubject);
    }

    private void queryMemeber() {
        suiFangModel.queryGroupMember(groupDetailEntity.getId(), new CommonObserver<List<GroupMemberEntity>>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(List<GroupMemberEntity> data) {
                adapter.clear();
                adapter.addAll(data);
                dismissLoadingDialog();
                List<NewUserEntity> list = new ArrayList<>();
                for (GroupMemberEntity entity : data) {
                    NewUserEntity userEntity = new NewUserEntity();
                    userEntity.setUserId(entity.getId());
                    userEntity.setImId(entity.getEasemobId());
                    userEntity.setAvatar(entity.getHeadPicture());
                    userEntity.setName(entity.getName());
                    userEntity.setRole(entity.getRole() + "");
                    list.add(userEntity);
                }
                userDao.saveContactList(list);
            }
        }, lifecycleSubject);
    }

    @Override
    protected void initEvent() {
        blockOfflineLayout.setOnClickListener(this);
        addMemberI.setOnClickListener(this);
        exitGroupB.setOnClickListener(this);
        adapter.setOnDeleteListener(new GroupDetailAdapter.OnDeleteListener() {
            @Override
            public void deleteMember(String userId) {
                deleteGroupMember(userId);
            }
        });
    }

    private void deleteGroupMember(String userId) {
        showLoadingDialog("删除中");
        suiFangModel.deleteGroupMember(groupId, userId, new CommonObserver<Object>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
                dismissLoadingDialog();
            }

            @Override
            public void onResult(Object data) {
                dismissLoadingDialog();
                showToast("删除成功");
                queryMemeber();
            }
        }, lifecycleSubject);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_switch_block_offline_message:
                toggleBlockOfflineMsg();
                break;
            case R.id.add_member:
                if (notEmpty(groupId)) {
                    PickContactsActivity.goPic(context, groupId, memberEntities);
                } else {
                    showToast("个人信息获取失败，暂不能添加");
                }
                break;
            case R.id.btn_exit_grp:
                exitGroup();
                break;
        }
    }

    public void changeName(View view) {
        ChangeGroupNameActivity.goActivity(context, group.getGroupName(), groupId, imGroupId);
    }

    private void exitGroup() {
        if (!notEmpty(groupId)) {
            showToast("暂无群信息，请稍后重试");
            return;
        }
        suiFangModel.exitGroup(groupId, UserHelper.getInstance(context).getUserId(), new CommonObserver<Object>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
            }

            @Override
            public void onResult(Object data) {
                showToast("退出成功");
                EventBusUtil.postEvent(new DeleteGroupMessage());
                if (ChatActivity.activityInstance != null) {
                    ChatActivity.activityInstance.finish();
                }
                finish();
            }
        }, lifecycleSubject);
    }

    private void toggleBlockOfflineMsg() {
        if (offlinePushSwitch.isSwitchOpen()) {
            EasePreferenceManager.getInstance().closeNotification(imGroupId);
            offlinePushSwitch.closeSwitch();
        } else {
            EasePreferenceManager.getInstance().openNotification(imGroupId);
            offlinePushSwitch.openSwitch();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateGroupMessage message) {
        if (message != null) {
            if (notEmpty(message.getGroupName())) {
                groupNameContentT.setText(message.getGroupName());
                setResult(Activity.RESULT_OK, new Intent());
            }
            if (message.isUpdateMember()) {
                if (groupDetailEntity != null) {
                    queryMemeber();
                } else {
                    queryGroupDetail();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }
}
